package com.kma.ncpractice2013.servlets;

import com.kma.ncpractice2013.auth.Crypto;
import com.kma.ncpractice2013.dao.UserDAO;
import com.kma.ncpractice2013.facade.MailFacade;
import com.kma.ncpractice2013.facade.MailFacadeImpl;
import com.kma.ncpractice2013.model.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * User: Viktor
 * Date: 11/19/13
 */
public class PasswordResetServlet extends HttpServlet
{
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{



	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String action = request.getParameter("action");
		if (action.equals("changepassword"))
		{
		String token = request.getParameter("token");
		UserDAO userDAO = new UserDAO();
		User user = userDAO.getByResetToken(token);
		String newpass = Long.toHexString(Double.doubleToLongBits(Math.random()));
		user.setPassword(Crypto.getHash(user.getSalt(), newpass, "SHA-256"));
		user.setPasswdResetToken(UUID.randomUUID().toString());
		userDAO.update(user);
		response.getWriter().print("Password has been reset to "+newpass+"\nChange password asap through user profile.");
		}
		else if (action.equals("sendmail"))
		{
			String token = UUID.randomUUID().toString();
			String email = request.getParameter("email");
			UserDAO userDAO = new UserDAO();
			User user = userDAO.getByLogin(email);
			if (user==null) response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/error.jsp")); //todo: add get prop to display message
			else
			{
				user.setPasswdResetToken(token);

				userDAO.update(user);
				MailFacade mail=new MailFacadeImpl();
				String subject = "Reservation System password reset confirmation";
				String letter = "Click on the following link to confirm password reset.\n" +
						                MailFacadeImpl.home + "/passwordReset?token=" + token +"&action=changepassword"+
						                "\nLink is valid for 1 day.";
				try
				{
					mail.sendLetter(email, subject, letter);

				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				response.getWriter().print("Email with instructions has been sent to "+email+"\nFollow it to reset your password.");
			}

		}
	}
}
